/*globals YUI database */
/*jslint white: true, browser: true, onevar: false, undef: true, nomen: false, eqeqeq: true, plusplus: true, bitwise: true, regexp: false, newcap: true, immed: true, strict: false */

YUI.add('v3-datatable-filter-datasource', function (Y) {

    var L = Y.Lang;

    function DataTableFilterDataSource() {
        DataTableFilterDataSource.superclass.constructor.apply(this, arguments);
    }

    Y.mix(DataTableFilterDataSource, {
        NS: "filterdatasource",
        NAME: "dataTableFilterDataSource",
        ATTRS: {
            recordset: {
                setter: "_setRecordSet"
            }
        }
    });

    Y.extend(DataTableFilterDataSource, Y.Plugin.Base, {
        _setRecordset: function (recordset) {
            recordset = recordset || new Y.Recordset(recordset);
            if (!recordset.hasPlugin('RecordsetFilter')) {
                recordset.plug(Y.Plugin.RecordsetFilter);
            }
            return recordset;
        },

        initializer: function () {
            var host = this.get('host');
            var recordset = host.get('recordset');
            recordset.plug(Y.Plugin.RecordsetFilter);
            this.set('recordset', recordset);
            this.load();
        },

        load: function (filter) {
            var recordset = this.get('recordset');
            var filteredRecordset;
            if (filter) {
                if (L.isFunction(filter)) {
                    filteredRecordset = recordset.filter.filter(filter);
                } else if (L.isObject(filter)) {
                    var key = filter.key || '';
                    var value = filter.value || '';
                    if (key && value) {
                        filteredRecordset = recordset.filter.filter(key, value);
                    }
                }
            } else {
                filteredRecordset = recordset;
            }

            if (filteredRecordset) {
                this.get("host").set("recordset", filteredRecordset);
            }
        }
    });

    Y.namespace("Plugin").V3_DataTableFilterDataSource = DataTableFilterDataSource;

}, '3.3.0', {
    requires: ['datatable-base', 'recordset-filter', 'plugin', 'datasource-local']
});
